﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Collections.ObjectModel;

namespace Catalina.Dal
{
	public abstract class ObjectReaderBase<T>
	{
		protected abstract IDbConnection GetConnection();
		protected abstract String CommandText { get; }
		protected abstract CommandType CommandType { get; }
		protected abstract Collection<IDataParameter> GetParameters(IDbCommand command);
		protected abstract MapperBase<T> GetMapper();

		public Collection<T> Execute()
		{
			Collection<T> collection = new Collection<T>();

			using (IDbConnection connection = GetConnection())
			{
				IDbCommand command = connection.CreateCommand();
				command.Connection = connection;
				command.CommandText = this.CommandText;
				command.CommandType = this.CommandType;

				foreach (IDataParameter param in this.GetParameters(command))
					command.Parameters.Add(param);

				try
				{
					connection.Open();

					using (IDataReader reader = command.ExecuteReader())
					{
						try
						{
							MapperBase<T> mapper = GetMapper();
							collection = mapper.MapAll(reader);
							return collection;
						}
						catch
						{
							throw;
						}
						finally
						{
							reader.Close();
						}
					}
				}
				catch
				{
					throw;
				}
				finally
				{
					connection.Close();
				}
			}
		}
	}
}
